package com.li.o2oSystem.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.li.o2oSystem.dao.ProductCategoryDao;
import com.li.o2oSystem.dao.ProductDao;
import com.li.o2oSystem.dto.ProductCategoryExecution;
import com.li.o2oSystem.entity.ProductCategory;
import com.li.o2oSystem.enums.ProductCategoryStateEnum;
import com.li.o2oSystem.exceptions.ProductCategoryOperationException;
import com.li.o2oSystem.service.ProductCategoryService;
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {
	@Autowired
	private ProductCategoryDao productCategoryDao;
	@Autowired
	private ProductDao productDao;
	/**
	 * 查询指定某个店铺下的所有商品类别信息
	 */
	public List<ProductCategory> getProductCategory(long shopId) {
		return productCategoryDao.queryProductCategory(shopId);
	}
	/**
	 * 批量添加商品类别
	 */
	@Transactional
	public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList)
			throws ProductCategoryOperationException {
		//空值判断
		if(productCategoryList != null && productCategoryList.size() > 0){
			try {
				int effectNum = productCategoryDao.batchInsertProductCategory(productCategoryList);
				if(effectNum < 0){//如果执行批量插入返回影响行数小于0
					throw new ProductCategoryOperationException("店铺类别创建失败");
				}else{
					return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
				}
			} catch (Exception e) {
				throw new ProductCategoryOperationException("batch add productCategory error:"+e.getMessage());
			}
		}else{
			return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
		}
	}
	/**
	 * 根据条件删除店铺类别
	 */
	@Transactional
	public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId)
			throws ProductCategoryOperationException {
		//解除tb_product中的商品与该productCategoryId的关联
		try {
			int effectNum = productDao.updateProductCategoryToNull(productCategoryId);
			if(effectNum < 0){
				throw new RuntimeException("商品类别更新失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException("delete productCategory error:"+e.getMessage());
		}
		//删除该productCategory
		try{
			int effectNum = productCategoryDao.deleteProductCategory(productCategoryId, shopId);
			if(effectNum < 0){//如果影响行数小于0
				throw new ProductCategoryOperationException("商品类别删除失败");
			}else{//返回删除成功状态
				return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
			}
		}
		catch(Exception e){
			throw new ProductCategoryOperationException("delete product category error:"+e.getStackTrace());
		}
	}

}
